// 获取应用实例
import { transPx } from "../../utils/util"
import { list as getList, hasPermission, apply, getDetailById, syncMiniUserInfo, getDirectoryTree } from '../../api/index'


const app = getApp<IAppOption>()
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		navHeight: 0,
		list: [],
		directoryId: '',
		title: '',
		isover: false,
		pageIndex: 1, pageSize: 20,
		pageTitle: ''
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		this.setData({
			navHeight: app.globalData.navHeight + app.globalData.statusHeight + transPx(152)
		})

		this.setData({
			directoryId: options?.directoryId || '',
			pageTitle: options?.title || ''
		})
		this.getList()
	},
	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {
    // 页面被用户分享时执行
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: 'EY汽车知识库，享你所想！'
        })
      }, 2000)
    })
    return {
      title: 'EY汽车知识库',
      path: '/page/index/index',
      promise 
    }
  },
	serach(e) {
		this.setData({
			title: e.detail.value,
			pageIndex: 1,
			isover: false
		})
		this.getList()
	},

	getList() {
    wx.showLoading({ title: '',mask: true})
		const { title, directoryId, pageIndex, pageSize } = this.data
		getList({ title, directoryId, pageIndex, pageSize }).then(res => {
      wx.hideLoading()
			this.setData({
				list: pageIndex == 1 ? res.data.rows : [...this.data.list, ...res.data.rows],
				isover: res.data.rows.length < pageSize
			})
		}).catch(err => {
      wx.hideLoading()
    })
	},
	// 翻页
	onReachBottom() {
		if (this.data.isover) return

		this.setData({
			pageIndex: this.data.pageIndex + 1
		})
		this.getList()
	},
  // 订阅消息开启
  subscriptionsSetting() {
    wx.getSetting({
      withSubscriptions: true,
      success (res) {
        console.log(res)
        if (res.subscriptionsSetting.mainSwitch && !res.subscriptionsSetting.itemSettings) {
          wx.requestSubscribeMessage({
            tmplIds: ['Ew99D7BIEeUItIOnNNU7mgoGa1emqekDaGdOn63bDqw'],
            success (res) { }
          })
        }
      }
    })
  },
	// 下载文件
  down(e) {
    const that = this
    
		if (!wx.getStorageSync('token')) {
      wx.showModal({
        title: '提示',
        content: '您还未登录，是否登录？',
        showCancel: true,
        confirmText: '去登录',
        confirmColor: '#FFE501',
        success: ({ confirm, cancel }) => {
          if (confirm) {
            wx.redirectTo({ url: '/pages/login/login' })
          }
        }
      })
      return
    }
    const item = e.currentTarget.dataset.item
    if (item.accessStatus === 1) {
      wx.navigateTo({
        url: `/pages/detail/detail?id=${item.id}&accessStatus=1`
      })
      return
    }
    wx.showLoading({ title: '',mask: true})
    hasPermission({
      documentId: item.id
    }).then(res => {
      wx.hideLoading()
      if (!res.data) {
        wx.showModal({
          title: '提示',
          content: '暂无访问权限，是否申请授权？',
          showCancel: true,
          confirmColor: '#FFE501',
          success: ({ confirm, cancel }) => {
            if (confirm) {
              wx.showLoading({ title: '',mask: true})
              apply({ documentId:item.id }).then(res1 => {
                wx.hideLoading()
                wx.showToast({title: '权限已申请，审核通过后，我们会及时通知您！', icon: 'none'})
                that.subscriptionsSetting()
              }).catch(res => {
                wx.hideLoading()
                that.subscriptionsSetting()
                wx.showToast({title: res.errorMsg, icon: 'none'})
              })
            }
          }
        })
      } else {
        wx.navigateTo({
          url: `/pages/detail/detail?id=${item.id}`
        })
      }
    }).catch(err => {
      wx.hideLoading()
    })
  },
})